package main

import (
	"flag"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"sync"

	"gitee.com/sjy/selfSendfile/client/protocols"
	"gitee.com/sjy/selfSendfile/common"
	"gitee.com/sjy/selfSendfile/utils"
	"github.com/astaxie/beego/logs"
)

func main() {
	var confFile string
	flag.StringVar(&confFile, "c", "", "config file")
	flag.Parse()

	conf := utils.Yaml[common.Config](confFile)
	sendFile := protocols.NewSendFile(conf.SendType)
	var wg sync.WaitGroup // 添加 WaitGroup 用于等待所有 goroutine 完成
	// 打开要发送的文件
	for _, path := range conf.SendFromPaths {
		wg.Add(1) // 每启动一个 goroutine 就增加计数
		go func(current string) {
			defer wg.Done() // goroutine 完成后减少计数
			task(current, conf, sendFile)
		}(path)
	}
	wg.Wait() // 等待所有 goroutine 完成
}

func task(current string, conf *common.Config, sendFile protocols.SendFile) {
	defer func() {
		if err := recover(); err != nil && err != io.EOF {
			logs.Error("%v", err)
		}
	}()
	file := &common.FileInfo{Filename: getFileName(current),
		CurrentPath: current,
		Size:        getFileSize(current),
		SendToPath:  conf.SendToPath}

	// 发送文件
	sendFile.Send(file, conf)
}

func getFileName(path string) string {
	filename := filepath.Base(path)
	if filename == "" {
		panic(fmt.Errorf("file name is empty: %v", path))
	}
	return filename
}

func getFileSize(path string) int64 {
	fileInfo, err := os.Stat(path)
	if err != nil {
		panic(fmt.Errorf("File Size Error: %v", path))
	}

	return fileInfo.Size()
}
